#include "luaexecuter.h"
#include "ui_luaexecuter.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

LuaExecuter::LuaExecuter(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LuaExecuter)
{
    ui->setupUi(this);

    m_sql = new QSqlQuery;

    m_lua_sql_exec = new LuaSqlExec(m_sql);
    m_lua_sql_next = new LuaSqlNext(m_sql);
    m_lua_sql_value = new LuaSqlValue(m_sql);

    m_lua_state = new QtLua::State();
    m_lua_state->openlib(QtLua::AllLibs);

    m_lua_sql_exec->register_(*m_lua_state, "sql.exec");
    m_lua_sql_next->register_(*m_lua_state, "sql.next");
    m_lua_sql_value->register_(*m_lua_state, "sql.value");

    QtLua::String filename = QtLua::String("../../acs/bin/qt-tools") + QtLua::Plugin::get_plugin_ext();
    m_lua_state->operator []("qtt") = QTLUA_REFNEW(QtLua::Plugin, filename);

    connect(m_lua_state, SIGNAL(output(QString)),
            this, SLOT(print(QString)));
    connect(ui->execAgainButton, SIGNAL(clicked()),
            this, SLOT(execLua()));
}

LuaExecuter::~LuaExecuter()
{
    delete m_lua_state;
    delete ui;
}

void LuaExecuter::execScript(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        //ui->statusLabel->setText(tr("Can't open query declaration, file didn't exist!"));
        return;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    m_luaScript = in.readAll();
    file.close();

    setWindowTitle(tr("Exec script: %1").arg(filename));
    execLua();
}

void LuaExecuter::print(const QString &str)
{
    if (str.at(0).toAscii() == 10) // ignore new line
        return;
    ui->consoleTextEdit->append(str);
}

void LuaExecuter::execLua()
{
    ui->consoleTextEdit->clear();
    //ui->consoleTextEdit->append(QString("<p style=\"color:#0000ff;\">Executing %1</font>").arg(filename));

    try {
        m_lua_state->exec_statements(m_luaScript);
    } catch (QtLua::String &e) {
        ui->consoleTextEdit->append(QString("<p style=\"color:#ff0000;\">Lua script error: %1</font>").arg(e.constData()));
    }
}
